const app = getApp()

export default {
	// 全局配置
	common: {
		baseToken: app.globalData.token,
		header: {},
		data: {},
		method: 'GET',
		dataType: 'json',
		timeout: 60000,
		appid: '',
	},
	// 请求返回promise
	request(options = {}) {
		// 请求头信息
		options.header = options.header || this.common.header;
		options.data = options.data || this.common.data;
		options.method = options.method || this.common.method;
		options.dataType = options.dataType || this.common.dataType;
		options.timeout = options.timeout || this.common.timeout;
		options.url = options.appip || this.common.appip;
		// 设置令牌请求头token
		options.header["Authorization"] = `${'Bearer ' + app.globalData.token}`;

		return new Promise((res, rej) => {
			wx.request({
				...options,
				success: (result) => {
					if (result.data.code == 10) {
						wx.showToast({
							title: result.data.message,
							icon: 'none',
							duration: 1500
						});
						wx.removeStorageSync('token');
						return res(new Promise((resolve) => {
							if (app.globalData.nowPages < 1) {
								wx.showModal({
									title: "提示",
									content: "暂未登录，是否进入授权手机号登录界面",
									success: (res) => {
										if (res.confirm) {
											setTimeout(() => {
												wx.navigateTo({
													url: "/pages/login/login"
												});
												resolve();
											}, 1500);
										}
									}
								});
							} else {
								resolve();
							}
						}));
					}
					return res(result);
				},
				fail: (error) => {
					console.log(error);
					return rej(error);
				}
			});
		});
	},
	get(appip, port, data = {}, options = {}) {
		options.port = port;
		options.appip = appip + port;
		options.data = data;
		options.method = 'GET';
		options.header = {
			'Content-type': 'application/json',
			'Authorization': 'Bearer'
		};
		return this.request(options);
	},
	post(appip, port, data = {}, options = {}) {
		options.port = port;
		options.appip = appip + port;
		options.data = data;
		options.method = 'POST';
		options.header = {
			'Accept': 'application/json, text/plain',
			'Content-type': 'application/json;charset=UTF-8'
		};
		return this.request(options);
	},
	repetition(options) {
		return this.request(options);
	},
	formpost(appip, url, data = {}, options = {}) {
		options.url = url;
		options.appip = appip;
		options.data = data;
		options.method = 'POST';
		options.header = {
			'Content-type': 'application/x-www-form-urlencoded'
		};
		return this.request(options);
	},
	_delete(appip, url, data = {}, options = {}) {
		options.url = url;
		options.appip = appip;
		options.data = data;
		options.method = 'DELETE';
		return this.request(options);
	},
	_put(appip, url, data = {}, options = {}) {
		options.url = url;
		options.appip = appip;
		options.data = data;
		options.method = 'PUT';
		return this.request(options);
	},
};